package Service.Impl;

import Dao.ArrangeInfoDao;
import Dao.StaffDao;
import Model.ArrangeInfo;
import Model.Department;
import Model.ElderInfo;
import Model.Staff;
import Service.ArrangeInfoService;
//import jdk.nashorn.internal.objects.NativeJSON;
import org.apache.commons.net.ntp.TimeStamp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import utils.Excel;

import java.io.InputStream;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

@Service("ArrangeInfoService")
public class ArrangeInfoServiceImpl implements ArrangeInfoService {
    @Autowired
    private ArrangeInfoDao arrangeInfoDao;
    @Autowired
    private StaffDao staffDao;

    //  获取全部信息
    @Override
    public List<ArrangeInfo> getAllArrangeInfoList() {
        System.out.println("service层：查看所有派工信息");
        return arrangeInfoDao.getAllArrangeInfoList();
    }

    //    获取单个老人排程日期信息
    @Override
    public List<ArrangeInfo> getDateArrangeInfo(String ArrangeID){
        System.out.println("service层：查询单个老人排程日期信息,输出ID："+ArrangeID);
        return arrangeInfoDao.getDateArrangeInfo(ArrangeID);
    }

    //    派工信息页面-搜索功能
    @Override
    public List<ArrangeInfo> findArrangeInfo(String servOrg,String settleCode,String servStatus,String elderName,String elderYbid,
                                             String elderId,String nursingName,String nursingYbid,String nursingId,String startDate ,
                                             String dueDate,String startTime){
        System.out.println("service层："+servOrg);
        System.out.println("service层："+servStatus);
        System.out.println("service层："+startDate);
        System.out.println("service层："+startTime);
        System.out.println("service层：进入dao层");
//        System.out.println(regionCode);
        return arrangeInfoDao.findArrangeInfo(servOrg,settleCode,servStatus,elderName,elderYbid,elderId,nursingName,
                nursingYbid,nursingId,startDate,dueDate,startTime);
    }

    //新增派工订单
    @Override
    public String insertArrangeInfo(String elderYbid,String OrgSettleCode,List<String> servContent,List<String>servID){
        System.out.println("service层：老人医保ID"+elderYbid);
        System.out.println("service层：机构结算代码"+OrgSettleCode);
        System.out.println("service层：服务内容"+servContent);
        System.out.println("service层：服务ID"+servID);
        //将服务项list转换为String字符串类型
        StringBuffer sb=new StringBuffer();
        for (String str:servContent) {
            sb.append(str+",");
        }
        sb.deleteCharAt(sb.lastIndexOf(","));
        String servContentToString=sb.toString();
        //将服务ID字符串化
        StringBuffer sb2=new StringBuffer();
        for (String str:servID) {
            sb2.append(str+",");
        }
        sb2.deleteCharAt(sb2.lastIndexOf(","));
        String servIDToString=sb2.toString();
        System.out.println("service层：服务Id字符串化"+servIDToString);
        //添加订单创建时间
        Date date = new Date();
        Timestamp arrange_time = new Timestamp(date.getTime());
        System.out.println("提交订单时间"+arrange_time);
        //添加订单状态：尚未添加时间的订单初始状态为无效
        String status="无效";
        System.out.println("订单状态："+status);
        this.arrangeInfoDao.insertArrangeInfo(elderYbid,OrgSettleCode,servContentToString,arrange_time,status,servIDToString);
        return "ok";
    }

    //派工订单添加服务项
    @Override
    public String insertArrangeContents(List<String> servContent){
        System.out.println("service层："+servContent);
        this.arrangeInfoDao.insertArrangeContents(servContent);
        return "AlreadyStored";
    }

    //派工日程安排页面：确定服务时间
    @Override
    public String choseServTime(String StartDate,String DueDate,String StartTime,String ServWorkLength,
                                String StaffYbid,List<String> ChosenWeekday,String ArrangeID,String serv_status){
        System.out.println("进入service层的choseServTime");
        System.out.println("开始日期："+StartDate+","+"结束日期："+DueDate);
        System.out.println("开始时间："+StartTime+","+"工作时长："+ServWorkLength);
        System.out.println("护士医保："+StaffYbid+","+"选择工作日(数组)："+ChosenWeekday);
        System.out.println("订单制定时间："+ArrangeID);
        //将选中的时间字符串化
        StringBuffer sb=new StringBuffer();
        for (String str:ChosenWeekday) {
            sb.append(str+",");
        }
        sb.deleteCharAt(sb.lastIndexOf(","));
        String ChosenWeekdayToString=sb.toString();
        //服务时间确定后，将订单状态更改为有效
        String status="有效";
        this.arrangeInfoDao.choseServTime(StartDate,DueDate,StartTime,ServWorkLength,StaffYbid,ChosenWeekdayToString,ArrangeID,status,serv_status);
        System.out.println("成功插入除每天工作时间以外的数据");
        this.arrangeInfoDao.cleanWeek(ArrangeID);
        //插入除每天工作时间以外的数据
        for (String str:ChosenWeekday) {
            System.out.println("输出每个选中的工作日："+str);
            String chosenDay=null;
            switch(str){
                case "周一":
                    chosenDay="serv_monday";break;
                case "周二":
                    chosenDay="serv_tuesday";break;
                case "周三":
                    chosenDay="serv_wednesday";break;
                case "周四":
                    chosenDay="serv_thursday";break;
                case "周五":
                    chosenDay="serv_friday";break;
                case "周六":
                    chosenDay="serv_saturday";break;
                case "周日":
                    chosenDay="serv_sunday";break;
            }
            this.arrangeInfoDao.insertEverydayTime(chosenDay,ArrangeID);
            //this.arrangeInfoDao.insertEverydayTime(chosenDay,ArrangeID);
        }
        return "AlreadyStoredTime";
    }


    //派工日程安排页面：确定服务时间
    @Override
    public int choseServShortTime(String StartDate,String DueDate,String StartTime,String ServWorkLength,
                                String StaffYbid,List<String> ChosenWeekday,String ArrangeID,String serv_status){
        System.out.println("进入service层的choseServTime");
        System.out.println("开始日期："+StartDate+","+"结束日期："+DueDate);
        System.out.println("开始时间："+StartTime+","+"工作时长："+ServWorkLength);
        System.out.println("护士医保："+StaffYbid+","+"选择工作日(数组)："+ChosenWeekday);
        System.out.println("订单制定时间："+ArrangeID);
        //将选中的时间字符串化
        StringBuffer sb=new StringBuffer();
        for (String str:ChosenWeekday) {
            sb.append(str+",");
        }
        sb.deleteCharAt(sb.lastIndexOf(","));
        String ChosenWeekdayToString=sb.toString();
        //服务时间确定后，将订单状态更改为有效
        String status="有效";
        this.arrangeInfoDao.choseServShortTime(StartDate,DueDate,StartTime,ServWorkLength,StaffYbid,ChosenWeekdayToString,ArrangeID,status,serv_status);
        System.out.println("成功插入除每天工作时间以外的数据");
        //this.arrangeInfoDao.cleanWeek(ArrangeID);
        //插入除每天工作时间以外的数据
        for (String str1:ChosenWeekday) {
            //System.out.println("输出每个选中的工作日："+str);
            String chosenDay=null;
            switch(str1){
                case "周一":
                    chosenDay="serv_monday";break;
                case "周二":
                    chosenDay="serv_tuesday";break;
                case "周三":
                    chosenDay="serv_wednesday";break;
                case "周四":
                    chosenDay="serv_thursday";break;
                case "周五":
                    chosenDay="serv_friday";break;
                case "周六":
                    chosenDay="serv_saturday";break;
                case "周日":
                    chosenDay="serv_sunday";break;
            }
            this.arrangeInfoDao.insertEverydayShortTime(chosenDay,ArrangeID);
            //this.arrangeInfoDao.insertEverydayTime(chosenDay,ArrangeID);
        }
        return 1;
    }

    //根据ID查找选择的服务日
    @Override
    public String findChosenDaybyID(String ArrangeID){
        System.out.println("service层：根据ID查询工作日："+ArrangeID);
        String findChosenDaybyID=this.arrangeInfoDao.findChosenDaybyID(ArrangeID);
        System.out.println("service层：根据ID查询工作日的结果："+findChosenDaybyID);
        return findChosenDaybyID;
    }

    //获取护工日程安排
    @Override
    public List<Map<String,Object>> findNurseArrangement(String NursingYbid,String whichWeek){
        System.out.println("service层：获取护工医保ID："+NursingYbid);
        List<ArrangeInfo> arrangeInfos=this.arrangeInfoDao.findNurseArrangement(NursingYbid,whichWeek);
        List<Map<String,Object>> NurseArrangement = new ArrayList<Map<String,Object>>();
        for(ArrangeInfo arrangeInfo:arrangeInfos){
            Map<String,Object> EachNurseArrangement=new HashMap<String,Object>();
            EachNurseArrangement.put("StartTime",arrangeInfo.getServ_start_time());
            EachNurseArrangement.put("WorkLength",arrangeInfo.getServ_worklength());
            EachNurseArrangement.put("ChosenDay",arrangeInfo.getChosen_weekday());
            EachNurseArrangement.put("Status",arrangeInfo.getServ_status());
            EachNurseArrangement.put("ElderName",arrangeInfo.getElder_name());
            EachNurseArrangement.put("ElderYbid",arrangeInfo.getElder_yb_id());
            EachNurseArrangement.put("EndTime",arrangeInfo.getServ_end_time());

            System.out.println("service层：arrangeInfo：");
            NurseArrangement.add(EachNurseArrangement);
        }
        System.out.println("service层：List<Map>："+NurseArrangement);
        return NurseArrangement;
    }


    //订单信息页面：删除
    @Override
    public String deleteArrangeOrder(int id) {
        System.out.println("service层：执行删除");
        this.arrangeInfoDao.deleteByPrimaryKey(id);
        System.out.println("删除成功");
        return "ok";
    }

    //订单信息页面：更新订单状态,过时订单的状态有效改无效
    @Override
    public String judgeStatus(){
        System.out.println("进入service层：judgeStatus");
        List<ArrangeInfo> arrangeInfos=this.arrangeInfoDao.getAllArrangeInfoList();
        //获取当前日期以及星期几
        Date date=new Date();
        Calendar WeekDay=Calendar.getInstance();
        WeekDay.setTime(date);
        int CurrentWeekDay=WeekDay.get(Calendar.DAY_OF_WEEK)-1;
        //判断订单状态
        for(ArrangeInfo EachArrangeInfo:arrangeInfos){
            System.out.println("service层："+EachArrangeInfo);
            int ArrangeInfoID=EachArrangeInfo.getId();
            if(EachArrangeInfo.getServ_due_date()!=null && EachArrangeInfo.getServ_status().equals("有效")){
                //情况一（已过期）需要的参数：将订单结束日期推迟一日，如：截止日期5/14的订单，在5/15过期
                Calendar calendar=new GregorianCalendar();
                calendar.setTime(EachArrangeInfo.getServ_due_date());
                calendar.add(calendar.DATE,1);
                Date orderDate=calendar.getTime();
                System.out.println("service层：延迟后的订单截止时间："+orderDate);
                //情况二（未开始）需要的参数：计算出下周日的时间
                int AddDay=14-CurrentWeekDay;
                System.out.println("service层：到下周周日增加的天数"+AddDay);
                Calendar NextWeekFinalDay=new GregorianCalendar();
                NextWeekFinalDay.setTime(date);
                NextWeekFinalDay.add(NextWeekFinalDay.DATE,AddDay);
                Date NextSunday=NextWeekFinalDay.getTime();
                System.out.println("service层：下周日的日期："+NextSunday);
                //情况三、四（本周和下周）需要的参数：
                int thisAddDay=7-CurrentWeekDay;
                System.out.println("service层：到本周周日增加的天数"+thisAddDay);
                Calendar thisWeekFinalDay=new GregorianCalendar();
                thisWeekFinalDay.setTime(date);
                thisWeekFinalDay.add(thisWeekFinalDay.DATE,thisAddDay);
                Date thisSunday=thisWeekFinalDay.getTime();
                System.out.println("service层：下周日的日期："+thisSunday);
                // 存储比较结果：若为1：date>orderDate，即过期；若为-1,则未过期
                if((date.compareTo(orderDate))==1){
                    //判断当前订单是否过期：
                    String Status="已过期";
                    this.arrangeInfoDao.judgeStatus(Status,ArrangeInfoID);
                    System.out.println("更新成功");
                }else if((EachArrangeInfo.getServ_start_date().compareTo(NextSunday))==1){
                    //若下周日时间为5/13 08：00，订单开始时间为周一5/14 00:00，则订单未开始
                    System.out.println("订单未开始");
                    String Status="订单未开始";
                    this.arrangeInfoDao.judgeStatus(Status,ArrangeInfoID);
                }else{
                    if((EachArrangeInfo.getServ_due_date().compareTo(thisSunday))==-1){
                        System.out.println("本周");
                        String Status="本周";
                        this.arrangeInfoDao.judgeStatus(Status,ArrangeInfoID);
                    }else {
                        System.out.println("下周");
                        String Status="下周";
                        this.arrangeInfoDao.judgeStatus(Status,ArrangeInfoID);
                    }
                }
            }
        }
        return "ok";
    }


//     * 派工信息页面：权限：查看派工单
    @Override
    public List<ArrangeInfo> getAllArrangeInfobySettleCode(String settleCode){
        return this.arrangeInfoDao.getAllArrangeInfobySettleCode(settleCode);
    }


//     * 派工单信息页面：权限：搜索当前机构下的派工信息
    @Override
    public List<ArrangeInfo> findArrangeInfobySettleCode(String thisSettleCode,String servOrg ,String servStatus,
                                                       String elderName ,String elderYbid,String elderId,String nursingName ,
                                                       String nursingYbid,String nursingId,String startDate ,String dueDate,
                                                       String startTime){
        return this.arrangeInfoDao.findArrangeInfobySettleCode(thisSettleCode,servOrg,servStatus,elderName,
                elderYbid,elderId,nursingName,nursingYbid,
                nursingId,startDate,dueDate,startTime);
    }


//微信小程序：护工登录
    @Override
    public String wechatLoginStaff(String StaffYbid,String password){
        System.out.println("service层：输出医保ID"+StaffYbid);
        System.out.println("service层：输出密码"+password);
        String staffPassword=this.staffDao.wechatGetPasswordbyYbid(StaffYbid);
        if(staffPassword!="" && staffPassword!=null){
            System.out.println("找到该护工");
            System.out.println("输出数据库的护工密码："+staffPassword);
           if(staffPassword.equals(password)){
               System.out.println("密码正确");
               return "correct";
           }else{
               return "errorPassword";
           }
        }else{
            System.out.println("未找到该护工");
            return "noStaff";
        }
    }

//    微信小程序：老人页面：查询到护工的服务老人
    @Override
    public List<Map<String,Object>> wechatElderBySatff(String StaffYbid) {
        System.out.println("service层：" + StaffYbid);
        List<ArrangeInfo> arrangeInfos = this.arrangeInfoDao.wechatElderBySatff(StaffYbid);
        List<Map<String, Object>> wechatElderBySatff = new ArrayList<Map<String, Object>>();
        for (ArrangeInfo arrangeInfo : arrangeInfos) {
            if(arrangeInfo.getServ_status().equals("有效")&&arrangeInfo.getServ_status().equals("本周")){
                Map<String, Object> EachArrangeInfo = new HashMap<String, Object>();
                //将时间按格式字符串化
                String strDateFormat = "HH:mm";
                SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
                String formatStartTime=sdf.format(arrangeInfo.getServ_start_time());
                String formatEndTime=sdf.format(arrangeInfo.getServ_end_time());
                //拼接开始和结束时间
                StringBuffer sb = new StringBuffer();
                sb.append(formatStartTime);
                sb.append("~");
                sb.append(formatEndTime);
                String WorkTimeToString = sb.toString();
                //将数据存到map中
                EachArrangeInfo.put("ArrangeID", arrangeInfo.getId());
                EachArrangeInfo.put("ElderName", arrangeInfo.getElder_name());
                EachArrangeInfo.put("ElderYbid", arrangeInfo.getElder_yb_id());
                EachArrangeInfo.put("ChosenDay", arrangeInfo.getChosen_weekday());
                EachArrangeInfo.put("WorkTime", WorkTimeToString);
                System.out.println("service层：map值" + EachArrangeInfo);
                wechatElderBySatff.add(EachArrangeInfo);
            }
        }
        System.out.println("service层：List<Map>" + wechatElderBySatff);
        return wechatElderBySatff;
    }

    @Override
    public List<Map<String, Object>> getMyelder(ArrangeInfo arrangeInfo) {
        return null;
    }

    //    微信小程序：健康信息页面：查询到老人的服务内容
    @Override
    public List<String> wechatServIDByID(String ArrangeID){
        System.out.println("service层：订单ID："+ArrangeID);
        String ElderServIDs=this.arrangeInfoDao.wechatServIDByID(ArrangeID);
        System.out.println("搜索成功：服务项ID字符串："+ElderServIDs);
        List<String> ServIDList=Arrays.asList(ElderServIDs.split(","));
        System.out.println("service层：服务项ID转数组："+ServIDList);
        return ServIDList;
    }

//    微信小程序：健康信息页面：根据订单id找到老人YBID
    @Override
    public String findElderYbidbyID(String ArrangeID){
        System.out.println("service层：订单ID："+ArrangeID);
        String ElderYbid=this.arrangeInfoDao.findElderYbidbyID(ArrangeID);
        System.out.println("service层：老人医保ID："+ElderYbid);
        return ElderYbid;
    }


    /**
     * 根据HgId获取派工单
     * @param arrangeInfo
     * @return
     */
    public List<ArrangeInfo> getArrangeByHgId(ArrangeInfo arrangeInfo){
        System.out.println("[Service层：根据HgId获取派工单]");
        return arrangeInfoDao.getArrangeByHgId(arrangeInfo);
    }

    //  传入excel
    @Override
    public String InputExcel(InputStream is, String originalFilename, String settleCode) {
        System.out.println("service层：传入excel文件");
        Map<String,Map<String,Object>> param = new HashMap<String,Map<String,Object>>();
        Map<String,Object> ginsengMap = new HashMap<String,Object>();
        List<ArrayList<Object>> list;
        if (originalFilename.endsWith(".xls")) {
            System.out.println("service层：是2003版的excel");
            list = Excel.readExcel2003(is);
        } else {
            System.out.println("service层：是2007版的excel");
            list = Excel.readExcel2007(is);
            System.out.println("service层：list.size() "+list.size());
        }
        for (int i=0,j=list.size();i<j;i++){
            List<Object> row = list.get(i);
            System.out.println("service层：当前i= "+i);
            System.out.println("service层：当前row= "+row);

            String ChosenWeekday= row.get(14).toString();
            System.out.println("service层：所选星期字符串："+ChosenWeekday);
            List<String> ChosenWeekdayList=Arrays.asList(ChosenWeekday.split(","));
            System.out.println("ChosenWeekdayList长度为："+ChosenWeekdayList.size());

            System.out.println("service层：所选星期转数组后："+ChosenWeekdayList);


            ginsengMap.put("serv_org", row.get(1).toString());
            ginsengMap.put("settle_code", row.get(2).toString());
            ginsengMap.put("arrange_time", row.get(3).toString());
            ginsengMap.put("nursing_yb_id", row.get(4).toString());
            ginsengMap.put("nursing_name", row.get(5).toString());
            ginsengMap.put("nursing_id", row.get(6).toString());
            ginsengMap.put("elder_yb_id", row.get(7).toString());
            ginsengMap.put("elder_name", row.get(8).toString());
            ginsengMap.put("elder_id", row.get(9).toString());
            ginsengMap.put("serv_start_time", row.get(10).toString());
            ginsengMap.put("serv_worklength", row.get(11).toString());
            ginsengMap.put("serv_start_date", row.get(12).toString());
            ginsengMap.put("serv_due_date", row.get(13).toString());
            ginsengMap.put("chosen_weekday", row.get(14).toString());
            ginsengMap.put("serv_content",row.get(15).toString());
            ginsengMap.put("serv_status",row.get(16).toString());
            param.put("keys", ginsengMap);
            this.arrangeInfoDao.InputExcel(param);
            System.out.println("service层：原始信息input成功");
            int currentId=this.arrangeInfoDao.getmaxID();
            System.out.println("service层：最大Id为："+currentId);
            this.arrangeInfoDao.CompleteInputExcel();
            for (String str:ChosenWeekdayList) {
              System.out.println("输出每个选中的工作日："+str);
              String chosenDay=null;
              switch(str){
                  case "周一":
                    chosenDay="serv_monday";break;
                  case "周二":
                    chosenDay="serv_tuesday";break;
                  case "周三":
                     chosenDay="serv_wednesday";break;
                  case "周四":
                     chosenDay="serv_thursday";break;
                  case "周五":
                     chosenDay="serv_friday";break;
                  case "周六":
                     chosenDay="serv_saturday";break;
                  case "周日":
                     chosenDay="serv_sunday";break;
              }
              this.arrangeInfoDao.NewOrderEveryDayTime(chosenDay);
            }
        }
        return "01";
    }
}


